import { expect } from '@jest/globals';
import fs from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.LiteEmptyAbility
  }
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const data = await fs.readFile(path.resolve(project.getModule('entry').moduleRootPath(), 'src/main/config.json'));

  // 解析JSON5文件
  const obj = JSON5.parse(data.toString());

  // 修改对象
  obj.module = { 'deviceType': 'smartVision' };

  // 将对象转换回JSON5字符串
  const json5Str = JSON5.stringify(obj);

  // 将修改后的字符串写回文件
  // eslint-disable-next-line max-len
  await fs.writeFile(path.resolve(project.getModule('entry').moduleRootPath(), 'src/main/config.json'), json5Str, 'utf8');

  const dataBuild = await fs.readFile(path.resolve(projectRoot, 'build-profile.json5'));

  // 解析JSON5文件
  const objJson = JSON5.parse(dataBuild.toString());

  // 修改对象
  objJson.app.product = {
    'compileSdkVersion': 10,
    'compatibleSdkVersion': 10,
    'runtimeOS': 'OpenHarmony'
  };

  // 将对象转换回JSON5字符串
  const json5ToStr = JSON5.stringify(objJson);

  // 将修改后的字符串写回文件
  await fs.writeFile(path.resolve(projectRoot, 'build-profile.json5'), json5ToStr, 'utf8');

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);
  // eslint-disable-next-line max-len
  const boolBin = (await fs.readdir(path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/outputs/default/bin'))).includes('entry-default-unsigned.bin');
  // eslint-disable-next-line max-len
  const boolHap = (await fs.readdir(path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/outputs/default'))).includes('entry-default-unsigned.hap');
  record.addStep('执行hap编译构建', result);
  expect(boolBin).toBe(true);
  expect(boolHap).toBe(true);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_OHOS_SMARTVISION_BUILD_HOS_API10_001')
  .description('OHOS瘦设备debug构建（smartvision)')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun('entry'));

// .load();
